import { config } from './global.config'

const _config = {
  authorization: {}
}

/* 构建属性
storageVariable：用于存储属性的变量
propertyName：属性名
setFun：对变量赋值时的回调
getFun：对变量获取时的回调 */
function buildProperty (storageVariable, propertyName, setFun, getFun) {
  return {
    configurable: true,
    enumerable: true,
    get: function () {
      const propertyValue = storageVariable[propertyName]
      if (getFun) {
        getFun(propertyValue)
      }
      return propertyValue
    },
    set: function (newAuthorization) {
      storageVariable[propertyName] = newAuthorization
      if (setFun) {
        setFun(newAuthorization)
      }
    }
  }
}

// 将 sessionStorage 与内存中变量同步
export function initConfigForBindingToken () {
  // 将本地配置和 sessionStorage 中的缓存进行合并
  const localAuthorization = {}
  const sessionAuthorization = JSON.parse(window.sessionStorage.getItem('authorization') || '{}')
  Object.assign(localAuthorization, config.authorization, sessionAuthorization)

  // 构建属性定义
  // const authorizationProperty = buildProperty(_config, 'authorization', val => window.sessionStorage.setItem('authorization', JSON.stringify(val)))
  const token = buildProperty(_config.authorization, 'token', val => {
    if (val) {
      window.sessionStorage.setItem('authorization', JSON.stringify(_config.authorization))
    } else {
      window.sessionStorage.clear()
    }
  })

  // 定义属性
  // Object.defineProperties(config, { authorization: authorizationProperty })
  // config.authorization = { authorization: {} }
  Object.defineProperties(config.authorization, {
    token
  })

  // config.authorization = localAuthorization
  Object.assign(config.authorization, localAuthorization)
}

// 初始化配置
// initConfigForBindingToken()
